//
//  BaseTableViewController.m
//  KutulusLaw
//
//  Created by Mahmood1 on 12/9/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BaseTableViewController.h"
#import "Constant.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "UserService.h"
#import "LoginViewController.h"
#import "RearViewController.h"
#import "KurtulusLawController.h"
#import "KStringEncoding.h"
#import "NSString+URLEncoding.h"
#import <MediaPlayer/MediaPlayer.h>
@interface BaseTableViewController()
{
	UITapGestureRecognizer *oneTap;
	MPMoviePlayerController *moviePlayer;
}
@end

@implementation BaseTableViewController

@synthesize tableView = _tableView, titleView = _titleView;

#pragma mark - UISearchBarDelegate
-(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
	[self.tableView addGestureRecognizer:oneTap];
	mySearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	[self touchSearchButton:self];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	if ([searchText length] == 0) {
		[mySearchBar resignFirstResponder];
		mySearchBar.text = @"";
		[self touchSearchButton:self];
	}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void)hideKeyboard
{
	[mySearchBar resignFirstResponder];
	[self.tableView removeGestureRecognizer:oneTap];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(55,6,280,30)];
    self.titleView.text =NSLocalizedString(@"Cases", nil);
    self.titleView.font = [UIFont boldSystemFontOfSize:18.0f];
    self.titleView.textColor = [UIColor whiteColor];
    self.titleView.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar addSubview: self.titleView];
	if ([self.navigationController.parentViewController respondsToSelector:@selector(revealGesture:)] && [self.navigationController.parentViewController respondsToSelector:@selector(revealToggle:)])
	{
		UIPanGestureRecognizer *navigationBarPanGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self.navigationController.parentViewController action:@selector(revealGesture:)];
		[self.navigationController.navigationBar addGestureRecognizer:navigationBarPanGestureRecognizer];
        
        
	}
    
    [self initControl];
	[self initializeFactory];
	_pageNumber = 1;
	_rowNumberPerPage = 20;
	_isPullToRefreshing = FALSE;
	_isEndedLoadMore = FALSE;
	_isLoadingMore = FALSE;
	
	activityLoading= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(100, 4, 37, 37)];
	[activityLoading setHidesWhenStopped:YES];
	self.tableView.tableFooterView = activityLoading;
	[self.tableView.tableFooterView setFrame:CGRectMake(0, 0, 37, 37)];
	
	oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    
    // Set required taps and number of touches
    [oneTap setNumberOfTapsRequired:1];
    [oneTap setNumberOfTouchesRequired:1];
	
}

- (void)initializeFactory {
	_searchFileDAO = [[KBaseSearchFileDAO alloc] init];
	_searchCommandDTO = [[KBaseSearchCommandDTO alloc] initWithSessionID:[CCommon shareSessionID] ];
	_cellFactory = [[KSearchFileCellFactory alloc] init];
	
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	_searchCommandDTO.sessionID = [CCommon shareSessionID];
	
	if (_ResponsedSearch == nil) {
		[self searchFile];
	}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) back {
	
	//Add code hide keyboard
	[mySearchBar resignFirstResponder];
	if ([self.navigationController.parentViewController isKindOfClass:[KurtulusLawController class]]) {
		KurtulusLawController *viewController = (KurtulusLawController *)self.navigationController.parentViewController;
		[viewController revealToggle:self];
	}
	
}
- (void)initControl
{
    mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 280.0f, 44.0f)]; 
    mySearchBar.delegate = self;
    mySearchBar.backgroundImage = [UIImage imageNamed:kImageBackgroundForRightSideView];
    [self.view addSubview:mySearchBar];
    self.tableView.tableHeaderView=mySearchBar;
    
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 30, 46)];
    [backButton setImage:[UIImage imageNamed:kImageSlidebar34x46] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    //self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationController.navigationBar addSubview:backButton];
 
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-gray"] forBarMetrics:UIBarMetricsDefault]; 
    
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:nil];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageBackgroundForRightSideView]]];
	
	//init Pull to Refresh
	_pullToRefresh = [[PullToRefreshView alloc] initWithScrollView:self.tableView];	[_pullToRefresh setDelegate:self];
	[self.tableView addSubview:_pullToRefresh];
	
	
	_progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
	_progressHUD.taskInProgress = YES;
	_progressHUD.progress = 0.5;
    _progressHUD.dimBackground = YES;
	
	_progressHUD.labelText = NSLocalizedString(@"Loading", nil);
	[_progressHUD setUserInteractionEnabled:YES];
	[self.view addSubview:_progressHUD];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if (_ResponsedSearch) {
		return [_ResponsedSearch countOfRows];
	}
	
    return 0;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	if (tableView == self.tableView) {
		if (indexPath.row < [_ResponsedSearch countOfRows]) {
			KBaseSearchFileDTO *searchFileDTO = [_ResponsedSearch objectInRowsAtIndex:indexPath.row];
			
			SearchFileCell *cell = [_cellFactory createSearchFileCell:searchFileDTO withOrderNumber:indexPath.row + 1];
			cell.delegate = self;
		

			return cell;
		}
	}
	
	return nil;
	
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.row%2==0) {
		cell.backgroundColor=[UIColor colorWithRed:220.0f/255 green:220.0f/255 blue:220.0f/255 alpha:1.0];
	}
	else
	{
		cell.backgroundColor=[UIColor colorWithRed:180.0f/255 green:180.0f/255 blue:180.0f/255 alpha:1.0];
	}
	
	if (_ResponsedSearch) {
		if (indexPath.row == [_ResponsedSearch countOfRows] - 1 && !_isLoadingMore) {
			[self loadMoreSearchFile];
		}
	}
	
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  
    
    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
	view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:kImageBackgroundForRightSideView]];
    
    return view;
    
}

- (void)cancel:(id)sender {
	
	if (_operation && [_operation isExecuting]) {
		[_operation cancel];
		[_cancelDownloadButton removeFromSuperview];
		[_progressHUD hide:YES];
		_progressHUD.detailsLabelText = nil;
	}
}
- (void)downFileAndOpen:(NSString *)fileUrl withFileName:(NSString *)fileName {
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];
	
	[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	_operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
	[_operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
		NSLog(@"%@", cachedResponse);
		
		return cachedResponse;
	}];
	
	[_operation setDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
		if (_progressHUD) {
			
			double convertedValue = totalBytesExpectedToRead;
			int multiplyFactor = 0;
			
			NSArray *tokens = [NSArray arrayWithObjects:@"bytes",@"KiB",@"MiB",@"GiB",@"TiB",nil];
			
			while (convertedValue > 1024) {
				convertedValue /= 1024;
				multiplyFactor++;
			}
			
			NSString *totalSize = [NSString stringWithFormat:@" %4.2f %@", convertedValue, [tokens objectAtIndex:multiplyFactor]];
			NSString *progressString = [NSString stringWithFormat:@"%@ %2d%%/",NSLocalizedString(@"Downloaded", nil),totalBytesRead * 100/totalBytesExpectedToRead];
			_progressHUD.detailsLabelText = [progressString stringByAppendingFormat:totalSize];
			if (totalBytesRead == totalBytesExpectedToRead) {
				_progressHUD.detailsLabelText = nil;
			}
		}
	}];
	
	_cancelDownloadButton = [UIButton  buttonWithType:UIButtonTypeCustom];
	[_cancelDownloadButton setFrame:CGRectMake(0, 0, 67, 24)];
	[_cancelDownloadButton setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
	[_cancelDownloadButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	_cancelDownloadButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"logout-67x24.png"]];
	
	CGPoint point = _progressHUD.textLabel.center;
	point.y += 30;
	[_cancelDownloadButton setCenter:point];
	[_cancelDownloadButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchDown];
	
	[_progressHUD addSubview:_cancelDownloadButton];
	
	[_progressHUD setTaskInProgress:YES];
	_progressHUD.labelText = NSLocalizedString(@"Loading", nil);
	[_progressHUD setMinSize:CGSizeMake(0, 170)];
	[_progressHUD show:YES];
	
	
	[_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
		[_progressHUD hide:YES];
		[_cancelDownloadButton removeFromSuperview];
		[_progressHUD setMinSize:CGSizeZero];
		
		NSString *documentsDirectory = [CCommon getUserDirectory];
		
		BOOL isDir;
		BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory isDirectory:&isDir];
		
		if (fileExists) {			
			if (!isDir) {				
				NSLog(@"Folder already exists...");
				NSError *error;	
				if (![[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory
											   withIntermediateDirectories:NO
																attributes:nil
																	 error:&error])
				{
					NSLog(@"Create directory error: %@", error);
				} else {
					isDir = TRUE;
				}
				
			}
		}
		
		if (isDir) {
			//make a file name to write the data to using the documents directory:
			NSString *filePath = [NSString stringWithFormat:@"%@/%@", 
								  documentsDirectory, fileName];
			//create content - four lines of text
			
			//save content to the documents directory
			
			NSError *error = nil;
			BOOL isSuccess = [responseObject writeToFile:filePath options:NSDataWritingAtomic error:&error];
			if (isSuccess) {
				[[NSUserDefaults standardUserDefaults] setObject:filePath forKey:fileUrl];
				NSURL *filePathUrl = [NSURL fileURLWithPath:filePath];
				controller = [UIDocumentInteractionController interactionControllerWithURL:filePathUrl];
				controller.delegate = self;
				NSLog(@"%@", controller.UTI);
				BOOL b = [controller presentOptionsMenuFromRect:CGRectZero inView:self.view animated:NO];
				if (!b){
					UIAlertView *view = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:[NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"Please install application support to open", nil), fileName] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
					[view show];
				}
			} else {
				UIAlertView *view = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:NSLocalizedString(@"Can not save this file to your device", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
				[view show];
			}
		}
		
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"Fail");
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
		[alert show];
		[_progressHUD hide:YES];
		[_cancelDownloadButton removeFromSuperview];
		[_progressHUD setMinSize:CGSizeZero];
	}];
	[_operation start];
}

- (void) moviePlayBackDidFinish:(NSNotification*)notification {
	[[NSNotificationCenter defaultCenter]
	 removeObserver:self
	 name:MPMoviePlayerPlaybackDidFinishNotification
	 object:moviePlayer];
	
	[moviePlayer stop];
	[moviePlayer.view removeFromSuperview];
	moviePlayer = nil;
}
#pragma SearchFileDelegate
- (void)searchFileCell:(SearchFileCell *)cell clickDocumentFile:(NSInteger)fileType relativePath:(NSString *)relativePath {
	NSString * fileUrl = [kURL_BASE stringByAppendingFormat:relativePath];
	NSLog(@"loading file :%@", [KStringEncoding urlEncodeUsingEncoding:fileUrl encoding:NSUTF8StringEncoding]);
	
	
	if ([fileUrl length] == 0) {
		return;
	}
	
	NSString *fileName = @"";
	for (int i = [fileUrl length] - 1; i >= 0; i--){
		NSRange range = {i, 1};
		
		NSString* c = [fileUrl substringWithRange:range];
		
		if ([c isEqualToString:@"/"] || [c isEqualToString:@"\\"]) {
			fileName = [fileUrl substringWithRange:NSMakeRange(i + 1, [fileUrl length] - (i + 1))];
			NSLog(@"%@",[KStringEncoding urlEncodeUsingEncoding:fileName encoding:NSASCIIStringEncoding] );
			fileUrl = [NSString stringWithFormat:@"%@/%@", [fileUrl substringToIndex:i + 1],  [KStringEncoding urlEncodeUsingEncoding:fileName encoding:NSASCIIStringEncoding]];
			break;
		}
	}

	
	switch (fileType) {
		case eFileTypePDF:
			
			break;
		case eFileTypePPT:
			
			break;
		case eFileTypeXLS:
			
			break;
		case eFileTypeConvertingVideo:
		{
			NSString *message = NSLocalizedString(@"Please wait for video file is converting on server", nil);
			[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil)otherButtonTitles:nil, nil ] show];
		}
			return;
			break;
		case eFileTypeMP3:
			
			break;
		case eFileTypeDOC:
			
			break;
		case eFileTypeConvertedVideo:
		{
			NSURL *url = [NSURL URLWithString:fileUrl];
			moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
			[moviePlayer setControlStyle:MPMovieControlStyleDefault];
			moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
			CGRect frame = self.view.frame;
//			if(self.interfaceOrientation ==UIInterfaceOrientationPortrait)
//				frame = CGRectMake(20, 69, 280, 170);
//			else if(self.interfaceOrientation ==UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation ==UIInterfaceOrientationLandscapeRight)
//				frame = CGRectMake(20, 61, 210, 170);
			[moviePlayer.view setFrame:frame];  // player's frame must match parent's
			[self.view addSubview: moviePlayer.view];
			[self.view bringSubviewToFront:moviePlayer.view];
			[moviePlayer setFullscreen:YES animated:YES];
			[[NSNotificationCenter defaultCenter] addObserver:self
													 selector:@selector(moviePlayBackDidFinish:)
														 name:MPMoviePlayerDidExitFullscreenNotification
													   object:moviePlayer];
			
			[moviePlayer prepareToPlay];
			[moviePlayer play];
			return;
			break;
		}
		default:
			NSLog(@"File Type is unexpected value.");
			break;
	}
	
		
	NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
	
	NSString *cachedPathFile = [userDefault stringForKey:fileUrl];
	
	if (cachedPathFile && [cachedPathFile length] > 0) {
		controller = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:cachedPathFile]];
		controller.delegate = self;
		NSLog(@"%@", controller.UTI);
		BOOL b = [controller presentOptionsMenuFromRect:CGRectZero inView:self.view animated:NO];
		if (!b){
			UIAlertView *view = [[UIAlertView alloc] initWithTitle: @"Message" message:[NSString stringWithFormat:@"Can not open %@ file. Please install support app.", fileName] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
			[view show];
		}
	} else {
		[self downFileAndOpen:fileUrl withFileName:fileName];
	}
}


- (void)touchSearchButton:(id)sender {
	[self.tableView removeGestureRecognizer:oneTap];
	[mySearchBar resignFirstResponder];
	if ([_searchCommandDTO.search isEqualToString:mySearchBar.text]) {
		return;
	} else {
		[_searchCommandDTO reset];
		_searchCommandDTO.search = [mySearchBar.text copy];
		[self searchFile];
		
	}
	
	
}

- (BOOL) searchFile{
	[_progressHUD show:YES];
	_searchCommandDTO.sessionID = [CCommon shareSessionID];
	
	BOOL b = [_searchFileDAO searchFile:_searchCommandDTO block:^(KBaseResponedSearchCommandDTO * searchCommnadDTO, NSError *error) {
		[_progressHUD hide:YES];
		
		if (searchCommnadDTO.isOK) {
			_isEndedLoadMore = NO;
			_ResponsedSearch = searchCommnadDTO;
			_searchCommandDTO.page++;
			
			[self.tableView reloadData];
		} else {
			//TODO: Handle INVALID_AUTH
			[self handleInvalidSession];
		}
		
		[_pullToRefresh finishedLoading];
		_isPullToRefreshing = NO;
	}];

	
	if (!b) {
		[_progressHUD hide:YES];
	}
	
	return b;
}
#pragma marks - Load More
- (void) setIsLoadingMore:(BOOL)isLoadingMore {
	if (isLoadingMore) {
		[activityLoading setHidden:NO];
		[activityLoading startAnimating];
	} else {
		[activityLoading stopAnimating];
	}
	_isLoadingMore = isLoadingMore;
	
}

- (BOOL) loadMoreSearchFile {

	if (_isEndedLoadMore) {
		return FALSE;
	}
	
	[self setIsLoadingMore:TRUE];
	_searchCommandDTO.sessionID = [CCommon shareSessionID];
	BOOL b = [_searchFileDAO searchFile:_searchCommandDTO block:^(KBaseResponedSearchCommandDTO * searchCommnadDTO, NSError *error) {
		[self setIsLoadingMore:FALSE];
		if (searchCommnadDTO.isOK) {
			if ([searchCommnadDTO countOfRows] == 0) {
				_isEndedLoadMore = YES ;
			} else {				
				[_ResponsedSearch.rows addObjectsFromArray:searchCommnadDTO.rows];
				_searchCommandDTO.page++;
				[self.tableView reloadData];
			}
		} else {
			[_progressHUD show:YES];
			[UserService checkLoginWithUserName:[CCommon shareUsername] pass:[CCommon sharePassword] :^(id dictionary, NSError *error) {
				if (error) {
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message: [error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
					[alert show];
					[_progressHUD hide:YES];
				}
				else
				{
					@try {
						NSLog(@"%@",dictionary);
						if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
							[CCommon setSesionID: [dictionary objectForKey: kKEY_SESSION_ID]];
							[_progressHUD hide:YES];
							[self loadMoreSearchFile];
						}
						else
						{
							LoginViewController *login = [[LoginViewController alloc] init];
							login.navigationItem.hidesBackButton = YES;
							login.isFristLogin = NO;
							[self.titleView removeFromSuperview];
							
							[self.navigationController pushViewController:login animated:YES];
						}
					}
					@catch (NSException *exception) {
						[_progressHUD hide:YES];
					}
					@finally {
						//
					}
				}
			}];

		}
	}];
	
	if (!b) {
		[self setIsLoadingMore:FALSE];
	}
	
	return b;
}

- (void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view {
	if (_isPullToRefreshing) {
		return;
	}
	
	[_searchCommandDTO reset];
	_searchCommandDTO.search = [mySearchBar.text copy];
	_isEndedLoadMore = FALSE;
	_isPullToRefreshing = YES;
	[_progressHUD show:YES];
	
	BOOL b = [self searchFile];

	if (!b) {
		NSLog(@"You can't search at this time");
		[_pullToRefresh finishedLoading];
		_isPullToRefreshing = NO;
		[_progressHUD hide:YES];
	}
}


- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
	return self;
}
//// If preview is supported, this provides the view controller on which the preview will be presented.
//// This method is required if preview is supported.
//// If presenting atop a navigation stack, provide the navigation controller in order to animate in a manner consistent with the rest of the platform.
//
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
	return  self.view.frame;
}
//
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
	return self.view;
}
- (void)documentInteractionControllerWillBeginPreview:(UIDocumentInteractionController *)controller {
	
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller {
	
}
// Preview presented/dismissed on document.  Use to set up any HI underneath.

- (void)documentInteractionControllerWillPresentOptionsMenu:(UIDocumentInteractionController *)controller {
	
}
- (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller{
	
}
// Options menu presented/dismissed on document.  Use to set up any HI underneath.

- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controlle {
	
}
- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller {
	
}
// Open in menu presented/dismissed on document.  Use to set up any HI underneath.

- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application {
	
}// bundle ID
- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application {
	
}

- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller canPerformAction:(SEL)action {
	return YES;
}
- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller performAction:(SEL)action {
	return  YES;
	
}


- (void) handleInvalidSession {
	[_progressHUD show:YES];
	[UserService checkLoginWithUserName:[CCommon shareUsername] pass:[CCommon sharePassword] :^(id dictionary, NSError *error) {
		if (error) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: [error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
			[alert show];
			[_progressHUD hide:YES];
		}
		else
		{
			@try {
				NSLog(@"%@",dictionary);
				if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
					[CCommon setSesionID: [dictionary objectForKey: kKEY_SESSION_ID]];
										[_progressHUD hide:YES];
					[self searchFile];
				}
				else
				{
					 LoginViewController *login = [[LoginViewController alloc] init];
					login.navigationItem.hidesBackButton = YES;
					login.isFristLogin = NO;
					[self.titleView removeFromSuperview];
					
					[self.navigationController pushViewController:login animated:YES];
				}
			}
			@catch (NSException *exception) {
				[_progressHUD hide:YES];
			}
			@finally {
				//
			}
		}
	}];
}

@end
